<template>
<div class="content" ref="contentElement">
  <!-- 加载状态 -->
  <template v-if="loading">
    <div
      v-for="i in 8"
      :key="i"
      class="card-skeleton"
    >
      <el-skeleton style="width: 100px; height: 180px;" variant="image" />
      <div style="padding: 8px; width: 100px;">
        <el-skeleton style="width: 100%; height: 1em;" variant="h3" />
        <div style="display: flex; justify-content: space-between; width: 100%;">
          <el-skeleton style="width: 50%; height: 1em;" variant="text" />
          <el-skeleton style="width: 30%; height: 1em;" variant="text" />
        </div>
      </div>
    </div>
  </template>

  <!-- 商品列表 -->
  <template v-else>
    <el-card
      v-for="item in listItem"
      :key="item.product_id"
      class="card"
      body-style="padding: 5px;"
      @click="openDetailDialog(item)"
    >
      <img :src="item.imageUrl" class="image" height="200" alt="空"/>
      <div class="text-area">
        <div>
          <el-text class="name">{{ item.brand }}      {{ item.name }}</el-text>
        </div>
        <div style="padding-top: 3px">
          <el-text>{{ item.description }}</el-text>
        </div>
        <div class="price_quantity">
          <el-text class="price">￥{{ item.price}}</el-text>
          <el-text class="quantity">销量:1000+ {{ item.sales }}</el-text>
        </div>
      </div>
    </el-card>
  </template>

  <!-- 加载更多提示 -->
  <div v-if="loadingMore" class="loading-more">正在加载更多...</div>
  <div v-if="!loading && !loadingMore && !hasMore" class="no-more">没有更多了</div>
  <!-- 商品详情弹窗 -->
  <el-dialog
    v-model="isDetailDialogVisible"
    width="80%"
    :before-close="closeDetailDialog"
  >
    <ProductDetail :product="currentProduct" /> <!-- 嵌入商品详情组件 -->
  </el-dialog>
</div>
</template>

<script lang="ts" setup>
import {ref, onMounted, onUnmounted, watch} from 'vue';
import { getBrandProductsWithConditions, userBehaviorApi,recommend } from '@/common/net/api'
import type { Product } from '@/common/types/goodsType';
import ProductDetail from "./ProductDetail.vue";
import { useCategoryStore } from '@/stores/category.ts'
import { useUserStore } from '@/stores/user.ts'
const CategoryStore = useCategoryStore()
const props = defineProps({
  searchParams: {
    type: Object,
    default: () =>{}
  }
});
const listItem = ref<Product[]>([]);
const loading = ref(true);
const loadingMore = ref(false);
const hasMore = ref(true);
const currentPage = ref(1);
let timer: number | null = null
const pageSize = ref(40);
// 弹窗状态
const isDetailDialogVisible = ref(false);
const currentProduct = ref<Product | null>(null); // 当前商品数据
// 打开商品详情弹窗
const openDetailDialog = (product: Product) => {
  currentProduct.value = product; // 设置当前商品数据
  console.log('组件加载，开始计时')
  timer = window.setInterval(() => {
    console.log('已停留6秒')
    let userBehavior = {
      behaviorType : 1,
      categoryId : product.categoryId,
      rootCategoryId : CategoryStore.getRootCategoryByChildId(product.categoryId)
    }
    userBehaviorApi(userBehavior)
    clearInterval(timer)
    timer = null
  }, 6000)
  isDetailDialogVisible.value = true; // 打开弹窗
};

// 关闭商品详情弹窗
const closeDetailDialog = () => {
  isDetailDialogVisible.value = false;
  if (timer) {
    console.log('已关闭')
    clearInterval(timer)
    timer = null
  }
};
// 滚动容器引用
const contentElement = ref<HTMLElement | null>(null);

// 获取商品数据
const fetchProducts = async (page: number, size: number) => {
  try {
    // 判断keyword、minPrice、maxPrice和categoryId是否都为空
    const isAllEmpty = !props.searchParams.keyword &&
      !props.searchParams.minPrice &&
      !props.searchParams.maxPrice &&
      !props.searchParams.categoryId;
    let useUser = useUserStore()
    let response;
    if (isAllEmpty&&useUser.token!=null) {
      // 如果都为空，调用recommend接口
      response = await recommend({
        current: page,
        size: size
      });
    } else {
      // 否则调用getBrandProductsWithConditions接口
      response = await getBrandProductsWithConditions({
        current: page,
        size: size,
        brandId: props.searchParams.brandId,
        productName: props.searchParams.keyword,
        minPrice: props.searchParams.minPrice,
        maxPrice: props.searchParams.maxPrice,
        categoryId: props.searchParams.categoryId
      });
    }

    if (page === 1) {
      listItem.value = response.data.records || [];
    } else {
      listItem.value = [...listItem.value, ...(response.data.records || [])];
    }
    hasMore.value = !!response.data.records && response.data.records.length === size;
  } catch (error) {
    console.error('获取商品失败:', error);
  } finally {
    loading.value = false;
    loadingMore.value = false;
  }
};

// 滚动加载逻辑
const handleScroll = () => {
  if (!contentElement.value || loadingMore.value || !hasMore.value) return;

  const { scrollTop, clientHeight, scrollHeight } = contentElement.value;
  if (scrollTop + clientHeight >= scrollHeight - 100) {
    loadingMore.value = true;
    currentPage.value++;
    fetchProducts(currentPage.value, pageSize.value);
  }
};

// 初始化滚动监听
const initScrollListener = () => {
  if (contentElement.value) {
    contentElement.value.addEventListener('scroll', handleScroll);
  }
};

watch(()=>props.searchParams,()=>{
  fetchProducts(1, 40);
})
// 组件挂载时加载数据并初始化滚动监听
onMounted(() => {
  fetchProducts(1, 40);
  initScrollListener();
});
// 组件卸载时移除滚动监听
onUnmounted(() => {
  if (contentElement.value) {
    contentElement.value.removeEventListener('scroll', handleScroll);
  }
});
</script>

<style scoped lang="scss">
.content {
  display: flex;
  flex-wrap: wrap;
  justify-content: left;
  gap:5px;
  overflow-y: auto; /* 允许滚动 */
  height: calc(100vh - 100px); /* 根据实际情况调整高度 */
  /* 隐藏滚动条 */
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE/Edge */
  &::-webkit-scrollbar {
    display: none; /* Chrome/Safari */
  }
}

.card {
  width: 195px;
  box-shadow: none;
  font-size: 14px;
  position: relative;
  height: 310px;
}
.card:hover{
  border: 3px solid red;
}

.card-skeleton {
  display: flex;
  flex-direction: column;
}

span {
  font-size: 12px;
}

.text-area {
  div {
    width: 100%;
    line-height: 1.2;
    span.name {
      font-weight: bold;
    }
  }
}

.image {
  width: 100%;
  object-fit: cover;
}

.bottom {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.button {
  font-size: 14px;
  margin-top: 5px;
  width: 100%;
}

.loading-more,
.no-more {
  width: 100%;
  text-align: center;
  padding: 10px;
  font-size: 14px;
  color: #999;
}

.price{
  font-size: 20px;
  color: red;
  padding-right: 15px;
}
.price_quantity{
  position: absolute;
  bottom: 5px;
}
</style>
